import sys
import os

from sklearn.preprocessing import StandardScaler

# 获取当前脚本的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 项目根目录（根据实际结构调整，可能是current_dir或其父目录）
project_root = os.path.dirname(current_dir)  # 若utils在父目录
# 或 project_root = current_dir  # 若utils与脚本同目录
sys.path.insert(0, project_root)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from ren_cai_liu_shi.utils.common import data_preprocessing
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
from xgboost import XGBClassifier

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.size'] = 15


def data_processing(path):
    data = data_preprocessing(path)
    train_data = data.copy()
    data.info()
    # print(data.describe())
    # print(data.isnull().sum())
    # 无缺失值
    train_data_col = ['Age', 'DistanceFromHome', 'MonthlyIncome', 'NumCompaniesWorked','TotalWorkingYears',
                      'TrainingTimesLastYear', 'YearsAtCompany','YearsInCurrentRole',
                      'YearsSinceLastPromotion', 'YearsWithCurrManager']          # 数值型特征
    categorical_col = ['BusinessTravel', 'Department', 'Education', 'EducationField', 'Gender',
                       'JobInvolvement', 'JobLevel', 'JobRole', 'JobSatisfaction', 'MaritalStatus',
                       'OverTime', 'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance']       # 类别型特征

    # 创建画布
    fig1 = plt.figure(figsize=(40, 40))
    fig2 = plt.figure(figsize=(40, 40))
    fig3 = plt.figure(figsize=(40, 40))
    fig4 = plt.figure(figsize=(45, 50))
    # 折线对比图绘制
    i = 1
    for col in train_data_col:
        ax = fig1.add_subplot(5, 2, i)
        sns.kdeplot(data=train_data[train_data['Attrition'] == 1], x=col, label='已离职', alpha=0.7, ax=ax,c='red')
        sns.kdeplot(data=train_data[train_data['Attrition'] == 0], x=col, label='未离职', alpha=0.7, ax=ax,c='blue')
        ax.set_title(col)
        ax.legend(title='离职情况')

        mean_0 = train_data[train_data['Attrition'] == 0][col].mean()
        mean_1 = train_data[train_data['Attrition'] == 1][col].mean()
        ax.axvline(mean_0, color='blue', linestyle='--', alpha=0.7, label=f'未离职均值: {mean_0:.2f}')
        ax.axvline(mean_1, color='red', linestyle='--', alpha=0.7, label=f'离职均值: {mean_1:.2f}')
        ax.legend()
        i = i + 1


    # 直方图与箱形图绘制
    j = 1
    for col in train_data_col:
        ax1 = fig2.add_subplot(5, 2, j)
        ax2 = fig3.add_subplot(5, 2, j)
        sns.histplot(data=train_data, x=col, hue='Attrition',
                     alpha=0.6, multiple='dodge',
                     palette={1: 'red', 0: 'blue'},
                     ax=ax1)
        ax1.set_title(f'{col} - 直方图')
        ax1.legend(['未离职', '已离职'])

        sns.boxplot(data=train_data, x='Attrition', y=col,
                   ax=ax2)
        ax2.set_title(f'{col} - 箱线图')
        ax2.set_xticks([0, 1])
        ax2.set_xticklabels(['未离职', '已离职'])
        j = j + 1

    # 类别型特征
    n = 1
    for col in categorical_col:
        ax = fig4.add_subplot(7, 2, n)
        sns.countplot(y=col, data=train_data,ax=ax)
        ax.set_title(f"{col} 类别分布")
        n = n + 1
    # plt.show()

    # 热编码处理
    one_hot_col = ['BusinessTravel', 'Department', 'EducationField', 'Gender','JobRole','MaritalStatus','Over18','OverTime']
    train_data = pd.get_dummies(train_data,columns=one_hot_col)
    scaler = StandardScaler()
    # 数值型特征标准化
    train_data[train_data_col] = scaler.fit_transform(train_data[train_data_col])
    # train_data.info()
    return train_data


if __name__ == '__main__':
    data_processing('../data/fig/train.csv')